package com.atguigu.yygh.msm.controller;

import com.atguigu.yygh.common.R;
import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "短信发送")
@RestController
@RequestMapping("/api/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    //redis模板
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation(value = "发送验证码短信")
    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone) {
        //1、跟据手机号查询redis，获取验证码
        String redisCode = redisTemplate.opsForValue().get(phone);
        //2、如果验证码存在，直接返回成功
        if(!StringUtils.isEmpty(redisCode)){
            return R.ok();
        }
        //3、如果不存在，生成验证码
        String code = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);
        //4、调用方法发送验证码短信
        // 阿里云要求必须先封装成map
        boolean isSend = msmService.send(phone,param);
        //5、发送验证码成功后，存入redis，设置为五分钟内有效
        if(isSend){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else{
            return R.error().message("发送失败");
        }

    }

}